package com.alinesno.cloud.operation.cmdb.third.headth;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;

/**
 * socket 检查
 * @author LuoAnDong
 * @since 2019年5月17日 上午11:09:25
 */
public class EchoClient {
	private final static int readerIdleTimeSeconds = 45 ;// 读操作空闲30秒
	private final static int connect_timeout = 45 ;// 读操作空闲30秒

	public boolean connect(int port, String host) throws Exception {
		// 配置客户端NIO线程组
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,connect_timeout);// 设置连接超时时间
			
			b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new ReadTimeoutHandler(readerIdleTimeSeconds));
							ch.pipeline().addLast(new WriteTimeoutHandler(readerIdleTimeSeconds));
						}
					});

			// 发起异步连接操作
			ChannelFuture f = b.connect(host, port).sync();
			boolean isSuccess = f.isDone() ; 
			return isSuccess ; 
		} finally {
			// 优雅退出，释放NIO线程组
			group.shutdownGracefully();
		} 
	}

	
}